package com.linkwechat.framework.security.filter;

import com.linkwechat.common.core.domain.entity.WeCorpAccount;
import com.linkwechat.common.tenant.TenantContextHolder;
import com.linkwechat.common.utils.ServletUtils;
import com.linkwechat.common.utils.sign.Base64;
import com.linkwechat.wecom.service.IWeCorpAccountService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
@Component
public class WeWorkChatAppTokenFilter extends OncePerRequestFilter {
    @Autowired
    IWeCorpAccountService weCorpAccountService;
    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        String weWorkAuthHead=httpServletRequest.getHeader("WeWorkAuth");
        if(StringUtils.isNotEmpty(weWorkAuthHead)&&weWorkAuthHead.equals("WeWorkAuthHeadLabel")){
            String authorization=httpServletRequest.getHeader("WeWorkAuthorization");
            if(StringUtils.isNotEmpty(authorization)){
                String[] strings=authorization.split(" ",2);
                String encodedToken=strings[1];
                String decodeToken=new String(Base64.decode(encodedToken), StandardCharsets.UTF_8);
                String[] userIdCorpId=decodeToken.split(":",2);
                String userId=userIdCorpId[0];
                String corpId=userIdCorpId[1];
                WeCorpAccount weCorpAccount =weCorpAccountService.findWeCorpByCorpId(corpId);
                TenantContextHolder.setTenantCode(weCorpAccount.getTenantCode());
            }
        }
        filterChain.doFilter(httpServletRequest,httpServletResponse);
    }
}
